/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.spb.support; 

import org.hibernate.Session;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List; 
import org.hibernate.Criteria;
/**
 *
 * @author macbook
 */
@SuppressWarnings("unchecked")
public class Dao <T extends Serializable> {
 
    private final Session session;
    private final Class<T> persistentClass;
    
	public Dao() {
        this.session = HibernateUtil.getSession();
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public Session getSession() {
        return session;
    } 
    
    public void save(T entity) {
        try {
            getSession().getTransaction().begin();
            getSession().saveOrUpdate(entity);
            getSession().getTransaction().commit();
        } catch (Throwable t) {
            getSession().getTransaction().rollback();
            t.printStackTrace();
        } finally {
            close();
        }
    }
    public void update(T entity) {
        try {
            getSession().getTransaction().begin();
            getSession().update(entity);
            getSession().getTransaction().commit();
        } catch (Throwable t) {
            getSession().getTransaction().rollback(); 
            t.printStackTrace(); 
        } finally { 
            close(); 
        } 
    }

    public void delete(T entity) {
        try {
            getSession().getTransaction().begin();
            getSession().delete(entity);
            getSession().getTransaction().commit();
        } catch (Throwable t) {
            getSession().getTransaction().rollback();
            t.printStackTrace();
        } finally { 
            close(); 
        } 
    } 
    
    public List<T> findAll(){ 
        return getSession().createCriteria(persistentClass).list(); 
    } 
     
    private void close() {
        if (getSession() != null && getSession().isOpen()) {
            getSession().close();
        }
    }   
    
    public Criteria createCriteria(){
        return getSession().createCriteria(persistentClass);
    }    
    
    public Criteria createCriteria(String nome){  
        return getSession().createCriteria(persistentClass,nome);
    }    
}
